package com.example.demo.controller;
import lombok.Getter;
import lombok.NoArgsConstructor;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import com.example.demo.config.MqttSubscriptionManager;
import com.example.demo.dto.ApiResponse;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import com.fasterxml.jackson.databind.DeserializationFeature;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.mqtt.inbound.MqttPahoMessageDrivenChannelAdapter;
import org.springframework.integration.mqtt.support.MqttHeaders;
import org.springframework.messaging.Message;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import com.example.demo.dto.DeviceMessageDTO;
@RestController
@RequestMapping("/api/devices")
public class DeviceController {


    private static final Logger LOG = LoggerFactory.getLogger(DeviceController.class);
    // 使用AtomicReference保证线程安全
    private final AtomicReference<Double> xCoordinate = new AtomicReference<>(0.0);
    private final double step = 10; // 步长值

    @PostMapping("/increase")
    public ApiResponse increaseDevice() {
        double newX = xCoordinate.updateAndGet(current -> current + step);
        Map<String, Double> coordinates = new HashMap<>();
        coordinates.put("x", newX);
        coordinates.put("y", 0.0);
        coordinates.put("z", 0.0);

        return new ApiResponse(true, "x坐标增加0.1成功", coordinates);
    }

    @PostMapping("/decrease")
    public ApiResponse decreaseDevice() {
        double newX = xCoordinate.updateAndGet(current -> current - step);
        Map<String, Double> coordinates = new HashMap<>();
        coordinates.put("x", newX);
        coordinates.put("y", 0.0);
        coordinates.put("z", 0.0);
        return new ApiResponse(true, "x坐标减少0.1成功", coordinates);
    }

    @PostMapping("/testConnect")
    public Map<String, Object> testConnect(@RequestBody Map<String, Object> payload) {
        Integer id = (Integer) payload.get("id");
        Map<String, Object> result = new HashMap<>();
        // 示例：id为偶数模拟连接成功，奇数失败
        boolean connected = id != null && id % 2 == 0;
        result.put("connected", connected);
        return result;
    }
    // 连接MQTT服务器的接口

    @Autowired
    private MqttPahoMessageDrivenChannelAdapter inboundAdapter;

    @PostMapping("/mqttconnect")
    public Map<String, Object> connectMqtt() {
        Map<String, Object> result = new HashMap<>();
        try {
            if (!inboundAdapter.isRunning()) {
                inboundAdapter.start();
            }
            result.put("success", inboundAdapter.isRunning());
        } catch (Exception e) {
            result.put("success", false);
            result.put("error", e.getMessage());
        }
        return result;
    }
    @PostMapping("/mqttdisconnect")
    public Map<String, Object> disconnectMqtt() {
        Map<String, Object> result = new HashMap<>();
        try {
            LOG.info("00j");
            inboundAdapter.setCompletionTimeout(1000); // 1秒超时
            inboundAdapter.stop();
//            if (inboundAdapter.isRunning()) {
//                inboundAdapter.stop();
//                LOG.info("duankailj");
//            }
            LOG.info("duankailj1111");
            result.put("success", !inboundAdapter.isRunning());
        } catch (Exception e) {
            result.put("success", false);
            result.put("error", e.getMessage());
        }
        return result;
    }

    @Autowired
    private MqttSubscriptionManager subscriptionManager;
    @PostMapping("/mqttsubscribe")
    @ResponseBody
    public Map<String, Object> mqttsubscribe(@RequestBody Map<String, String> body) {
        Map<String, Object> result = new HashMap<>();
        try {
            String topic = body.get("topic");
            if (topic == null || topic.trim().isEmpty()) {
                result.put("success", false);
                result.put("msg", "订阅主题不能为空");
                return result;
            }
            subscriptionManager.subscribe(topic, 0); // 0为QoS，可根据需要调整
            result.put("success", true);
            result.put("msg", "订阅成功");
        } catch (Exception e) {
            result.put("success", false);
            result.put("msg", "订阅异常: " + e.getMessage());
        }
        return result;
    }
    // 用于保存实时控制开关状态
    private volatile boolean realtimeEnabled = false;
    @PostMapping("/realtime")
    public Map<String, Object> setRealtime(@RequestBody Map<String, Object> body) {
        Map<String, Object> result = new HashMap<>();
        try {
            Boolean enable = (Boolean) body.get("enable");
            this.realtimeEnabled = Boolean.TRUE.equals(enable);
            result.put("success", true);
            result.put("msg", enable ? "实时控制已开启" : "实时控制已关闭");
        } catch (Exception e) {
            result.put("success", false);
            result.put("msg", "操作异常: " + e.getMessage());
        }
        return result;
    }
    @Autowired
    private SimpMessagingTemplate messagingTemplate;

    @ServiceActivator(inputChannel = "mqttInputChannel")
    public void handleMqttMessage(Message<String> message) {
        if (!realtimeEnabled) {
            return; // 开关关闭时不处理
        }
        String payload = message.getPayload();
        LOG.info("Received MQTT message: {}", payload);
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            // 配置 Jackson 忽略未知属性
            objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

            if (payload.contains("F0") && payload.contains("W0")) {
                // 处理压力数据消息
                DeviceMessageDTO.PressureData pressureData = objectMapper.readValue(payload, DeviceMessageDTO.PressureData.class);
                LOG.info("Pressure data message: {}", pressureData);
//                LOG.info("Pressure data message: F0={}, F1={}, F2={}, F3={}, F4={}, F5={}, F6={}, F7={}, F8={}, W0={}, W1={}, W2={}, W3={}, W4={}",
//                        pressureData.getF0(), pressureData.getF1(), pressureData.getF2(), pressureData.getF3(),
//                        pressureData.getF4(), pressureData.getF5(), pressureData.getF6(), pressureData.getF7(),
//                        pressureData.getF8(), pressureData.getW0(), pressureData.getW1(), pressureData.getW2(),
//                        pressureData.getW3(), pressureData.getW4());
                messagingTemplate.convertAndSend("/topic/mqttPressureData", pressureData);
            }   else {
                // 处理原有 Coordinates 消息
                // DeviceMessageDTO.Coordinates coords = objectMapper.readValue(payload, DeviceMessageDTO.Coordinates.class);
                DeviceMessageDTO.Coordinates coords = new ObjectMapper().readValue(message.getPayload(), DeviceMessageDTO.Coordinates.class);
                LOG.info("JSON message: {}", coords);
                messagingTemplate.convertAndSend("/topic/mqttData", coords);
            }
        } catch (Exception e) {
            LOG.error("Failed to parse MQTT payload: {}", payload, e);
        }
    }

}

